package org.dc.activity.workDay;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.TimePicker;
import org.dc.R;
import org.dc.entity.Visit;
import org.dc.service.PersistenceManager;
import org.dc.view.IntervalTimeChangeListener;

import java.util.Calendar;
import java.util.Date;

/**
 * @user: Vladimir Chernishov
 * @date: 3/8/12
 * @time: 9:00 PM
 */
public class NewVisitScr extends Activity {

    private Calendar date;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_visit);
        date = (Calendar) getIntent().getSerializableExtra("Calendar");
        if(date == null){
            date = Calendar.getInstance();
        }
        TimePicker timePicker = (TimePicker) findViewById(R.id.newVisitTime);
        timePicker.setIs24HourView(true);
        timePicker.setCurrentHour(date.get(Calendar.HOUR_OF_DAY));
        timePicker.setCurrentMinute(date.get(Calendar.MINUTE));
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String value = prefs.getString("minuteInterval", null);
        int interval = (value == null || value.equals("0")) ? 30 : Integer.valueOf(value);

        timePicker.setOnTimeChangedListener(new IntervalTimeChangeListener(interval));

        TimePicker length = (TimePicker) findViewById(R.id.newVisitLength);
        length.setIs24HourView(true);
        length.setCurrentHour(0);
        length.setCurrentMinute(30);
        length.setOnTimeChangedListener(new IntervalTimeChangeListener(interval));
    }
    
    
    public void okClicked(View view){
        Visit visit = new Visit();
        EditText edit = (EditText)findViewById(R.id.newVisitDescription);
        visit.setDescription(edit.getText().toString());
        TimePicker timePicker = (TimePicker) findViewById(R.id.newVisitTime);

        visit.setDate(date.getTime());
        visit.setTime(timePicker.getCurrentHour() * 60 + timePicker.getCurrentMinute());
        visit.setCreated(new Date());
        TimePicker length = (TimePicker) findViewById(R.id.newVisitLength);
        visit.setLength(length.getCurrentHour()*60 + length.getCurrentMinute());
        PersistenceManager.getVisitDao(this).save(visit);

        finish();
    }

    public void cancelClicked(View view){
        finish();
    }

}
